import * as _ from 'lodash'
class Personno {

  setTimeOutId: NodeJS.Timeout | null = null;
  setIntervalId: NodeJS.Timeout | null = null;
  countDownDom: HTMLDivElement;
  initSNum: number = 10;
  sNum: number;
  constructor(
    public stus = document.querySelectorAll('li') as NodeListOf<HTMLLIElement>,
    public startBtn = document.querySelector('.btn-start') as HTMLButtonElement,
    public endBtn = document.querySelector('.btn-end') as HTMLButtonElement,

  ) {
    this.sNum = this.initSNum,
      this.countDownDom = document.querySelector('.countdown') as HTMLDivElement,
      this.countDownDom.innerText = String(this.sNum)
    this.initEventListeners()
  }

  public initEventListeners(): void {
    this.startBtn.addEventListener('click', _.debounce(() => this.startBtnHandler(), 250));
    this.endBtn.addEventListener('click', () => this.endBtnHandler());
  }
  //开始
  startBtnHandler = (): void => {
    this.countDown();
    this.setRandomStuAddActive();
  }
  //暂停
  endBtnHandler = (): void => {
    this.initClear()
  }

  // 倒计时
  countDown(): void {
    this.setIntervalId = setInterval(() => {
      console.log(this.sNum);
      // 把倒计时的秒数显示到页面上
      this.countDownDom.innerText = String(this.sNum)
      this.sNum--
      // 判断是否小于等于0 清除定时任务
      if (this.sNum <= 0) {
        this.initClear()
      }

    }, 1000);
  }

  // 清除定时器
  initClear(): void {
    clearInterval(this.setIntervalId!)
    clearTimeout(this.setTimeOutId!)

    // 定义显示倒计时的秒数
    this.sNum = this.initSNum
    this.countDownDom.innerText = String(this.sNum)
  }

  // 去除active
  clearStuActiveAll(): void {
    this.stus.forEach(stu => {
      stu.classList.remove('active')
    });
  }

  // 随机添加active
  setRandomStuAddActive = (): void => {
    this.clearStuActiveAll();
    // 随记获取一名学生对应的索引值
    let rand = Math.floor(Math.random() * this.stus.length)  // 0.234  ~ 20.234234 => 向下取整  0~20
    this.stus[rand].classList.add('active')

    this.setTimeOutId = setTimeout(this.setRandomStuAddActive, 100);
  }

}
export default Personno